<template>
  <div style="height: 100%;background:#F7F8FA;">
    <el-form :model="form" :rules="rules" ref="formRule" class="form-inline formList"  label-width="110px">
      <p style="font-size: 18px; margin-bottom: 20px" class="big_title_style">活动设置</p>
      <div style="margin-left: 20px">
        <el-form-item label="活动类型" required><span style="font-size: 16px; color: #606266; font-weight: bold">{{
            activityName
          }}</span></el-form-item>
        <el-form-item label="活动名称" prop="activityName">
          <el-input style="width: 400px" v-model="form.activityName" placeholder="请输入25字以内的活动名称" :disabled="true"></el-input>
        </el-form-item>

        <!-- 套餐活动所传参数 -->
        <el-form-item label="套餐图片" prop="packagesUrl" v-if="activityType && activityType == 'packages'">
            <imageArraySize style="margin-left: 40px;" :imageStr.sync="form.packagesUrl" :size="500" :disabled="true"
              :key="form.packagesUrl" :msg="'图片要求：宽750px，高563px，大小500KB以内。'" :limit="1" ref="childss">
            </imageArraySize>
        </el-form-item>
        <el-form-item label="充值金额" prop="rechargePriceStr" v-if="activityType && activityType == 'recharge' ">
                  <el-input style="width: 400px" v-model="form.rechargePriceStr" placeholder="请输入充值金额" maxlength="9"
                    @input="form.rechargePriceStr = oninput(form.rechargePriceStr, 2)"></el-input>
                </el-form-item>
        <el-form-item label="套餐价格" prop="packagesPriceStr" v-if="activityType && activityType == 'packages'">
          <el-input style="width: 400px" v-model="form.packagesPriceStr" placeholder="请输入套餐价格"
            @input="form.packagesPriceStr = oninput(form.packagesPriceStr, 2)" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="套餐库存" prop="packagesStock" v-if="activityType && activityType == 'packages'">
          <el-input style="width: 400px" v-model="form.packagesStock" placeholder="请输入套餐库存" :disabled="true"
            oninput="value=value.replace(/[^\d]/g,'')" ></el-input>
        </el-form-item>
        <el-form-item label="限购数量" prop="packagesLimit" v-if="activityType && activityType == 'packages'">
          <el-input style="width: 400px" v-model="form.packagesLimit" placeholder="请输入限购数量" :disabled="true"
           oninput="value=value.replace(/[^\d]/g,'')" ></el-input>
        </el-form-item>


        <el-form-item label="活动商品" prop="activityInfoProVo" >
          <div class="selectProduct" @click="selectProduct">
            <a style="color: #666; font-size: 12px" :disabled="true">+ 选择商品</a>
          </div>

          <!-- =====================已选的商品列表组件======================= -->
          <selected v-if="selectedData && selectedData.length > 0" :selectedData="selectedData" :activityType="activityType"
            ref="authTree" style="margin-top: 10px;" :disabled="true">
          </selected>

        </el-form-item>


        <el-form-item label="活动时间" prop="beginTime">
          <el-date-picker v-model="timeValue" type="datetimerange" range-separator="至" start-placeholder="开始日期" style="width: 400px"
            end-placeholder="结束日期" @change="getSTime" :disabled="true">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="预热时间" v-if="activityType != 'bargain'" prop="preHeatTime">
          <el-date-picker clearable size="small" v-model="form.preHeatTime" type="datetime" :disabled="true" style="width: 400px"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择预热时间">
          </el-date-picker>
          <span style="color: #666;margin-left: 10px">(前端界面展示活动的时间)</span>
        </el-form-item>

        <!-- <el-form-item label="规则描述" style="margin-left: 10px">
          <el-input style="width: 400px" type="textarea" v-model="form.ruleDesc"></el-input>
        </el-form-item>
        <el-form-item label="详细描述" style="margin-left: 10px">
          <el-input style="width: 400px" type="textarea" v-model="form.detailedDesc"></el-input>
        </el-form-item> -->
        <div style="margin-bottom: 60px">
          <el-form-item label="预留支付时长">
            <el-input style="width: 400px" v-model="form.payMinute" :disabled="true"></el-input>
            <span style="color: #666;margin-left: 10px">分钟 (建议 5 - 60 分钟)</span>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <!-- 选择商品 -->
    <commoditytab v-if="open" @toCloseBox="toCloseBox" @multipleSelection="multipleSelection"
      :selectedData="selectedData" :flag="open" :proUids="proUids" ref="selTable">
    </commoditytab>

    <div class="yhqBottom">
      <el-button type="primary" style="color: #fff" @click="preservation" :disabled="true">保存</el-button>
      <el-button @click="close()">取消</el-button>
    </div>
  </div>
</template>

<script>
  import {
    getInfo,
    addInfo,
    updateInfo,
    getInfoProUid,
  } from "@/api/activity/info";

  import selected from "./selectTable.vue";
  import commoditytab from "@/components/Activity/commodityTab";
  import imageArraySize from "@/components/ImageUpload/imageArraySize";
  export default {
    components: {
      selected,
      commoditytab,
      imageArraySize,
    },
    props: {

    },
    data() {
      return {
        activityName: null,
        activityType: null,
        timeValue: [],
        selectedData: [],
        open: false,
        form: {
          payMinute: 5,
        },
        proUids: [],
        rules: {
          activityName: [{
            required: true,
            message: "不能为空",
            trigger: "blur",
          }, ],
          preHeatTime: [{
            required: true,
            message: "不能为空",
            trigger: "blur",
          }, ],
          beginTime: [{
            required: true,
            message: "不能为空",
            trigger: "blur",
          }, ],
          activityInfoProVo: [{
            required: true,
            message: "不能为空",
            trigger: "blur",
          }, ],
          packagesUrl: [{
            required: true,
            message: "不能为空",
            trigger: "blur",
          }],
          rechargePriceStr: [{
            required: true,
            message: "不能为空",
            trigger: "blur",
          }],
          packagesPriceStr: [{
            required: true,
            message: "不能为空",
            trigger: "blur",
          }],
          packagesStock: [{
            required: true,
            message: "不能为空",
            trigger: "blur",
          }],
          packagesLimit: [{
            required: true,
            message: "不能为空",
            trigger: "blur",
          }],
        },
        oninput(num, limit) {
          var str = num;
          var len1 = str.substr(0, 1);
          var len2 = str.substr(1, 1);
          if (str.length > 1 && len1 == 0 && len2 != ".") {
            str = str.substr(1, 1);
          }
          if (len1 == ".") {
            str = "";
          }
          if (str.indexOf(".") != -1) {
            var str_ = str.substr(str.indexOf(".") + 1);
            if (str_.indexOf(".") != -1) {
              str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
            }
          }
          //正则替换
          str = str.replace(/[^\d^\.]+/g, ""); // 保留数字和小数点
          if (limit / 1 === 1) {
            str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, "$1"); // 小数点后只能输 1 位
          } else {
            str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, "$1"); // 小数点后只能输 2 位
          }
          return str;
        },
      };
    },
    created() {
      this.getDataInfo();
      this.activityType = this.$route.query.activityType;
      this.activityName = this.$route.query.activityName;
    },
    methods: {
      getDataInfo() {
        this.form = {}
        this.$forceUpdate();
        const activityUid = this.$route.query && this.$route.query.activityUid;
        if (activityUid) {
          getInfo(activityUid).then((response) => {
            this.form = response.data;
            this.activityType = this.form.activityType
            this.activityName = this.form.activityTypeName
            this.selectedData = this.form.activityInfoProVo;

            if(this.activityType){
              if(this.activityType == 'packages'){
                this.form.packagesPriceStr = parseFloat(this.form.packagesPrice)/100;
              }else if(this.activityType == 'recharge'){
                this.form.packagesPriceStr = parseFloat(this.form.packagesPrice)/100;
                this.form.rechargePriceStr = parseFloat(this.form.rechargePrice)/100;
              }
            }

            if (this.selectedData && this.selectedData.length > 0) {
              for (let i = 0; i < this.selectedData.length; i++) {
                this.selectedData[i] = JSON.parse(
                  JSON.stringify(this.selectedData[i]).replace(
                    "proName",
                    "productName"
                  )
                );
                this.selectedData[i] = JSON.parse(
                  JSON.stringify(this.selectedData[i]).replace(
                    "proUid",
                    "productUid"
                  )
                );
                this.selectedData[i] = JSON.parse(
                  JSON.stringify(this.selectedData[i]).replace(
                    "imgUrl",
                    "carouselImgOne"
                  )
                );
              }
            }
            this.timeValue.push(this.form.beginTime);
            this.timeValue.push(this.form.endTime);
          });
        }
      },
      //提交
      preservation() {
        this.form.activityType = this.activityType;
        if (this.form.beginTime && this.form.preHeatTime) {
          let beginTime = new Date(this.form.beginTime);
          let preHeatTime = new Date(this.form.preHeatTime);
          if (beginTime < preHeatTime) {
            return this.msgError("预热时间需在开始时间之前");
          }
        }

        //父组件注册子组件后绑定ref，调用子组件的函数获取数据
        if (this.selectedData && this.selectedData.length > 0) {
          this.selectedData = this.$refs.authTree.getData();
        }

        for (let i = 0; i < this.selectedData.length; i++) {
          this.selectedData[i] = JSON.parse(
            JSON.stringify(this.selectedData[i]).replace("productName", "proName")
          );
          this.selectedData[i] = JSON.parse(
            JSON.stringify(this.selectedData[i]).replace("productUid", "proUid")
          );
          this.selectedData[i] = JSON.parse(
            JSON.stringify(this.selectedData[i]).replace("carouselImgOne", "imgUrl")
          );
          if (this.form.activityType != "bargain" && this.form.activityType != "group") {
            this.selectedData[i].needPerson = 0;
          }

          this.selectedData[i].activityPrice =
            parseInt(parseFloat(this.selectedData[i].activityPriceStr)*100);
        }
        console.log(this.selectedData);

        if(this.form.activityType && this.form.activityType == 'packages' || this.form.activityType == 'recharge'){
          this.form.packagesPrice = parseInt(parseFloat(this.form.packagesPriceStr)*100);
          if(this.form.rechargePriceStr)
            this.form.rechargePrice = parseInt(parseFloat(this.form.rechargePriceStr)*100);
          // 提交时需定义childss，后面的方法随便定义selectImgs
          this.$refs.childss.selectImgs();
        }

        this.$set(this.form, "activityInfoProVo", this.selectedData);
        console.log(this.form);
        this.$refs["formRule"].validate((valid) => {
          if (valid) {
            const activityUid = this.$route.query && this.$route.query.activityUid;
            if (activityUid) {
              this.form.activityUid = activityUid;
              updateInfo(this.form).then((respone) => {
                this.msgSuccess("修改成功");
                this.close();
              });
            } else {
              addInfo(this.form).then((respone) => {
                this.msgSuccess("添加成功");
                this.close();
              });
            }
          }else{
            for (let i = 0; i < this.selectedData.length; i++) {
              this.selectedData[i] = JSON.parse(
                JSON.stringify(this.selectedData[i]).replace(
                  "proName",
                  "productName"
                )
              );
              this.selectedData[i] = JSON.parse(
                JSON.stringify(this.selectedData[i]).replace(
                  "proUid",
                  "productUid"
                )
              );
              this.selectedData[i] = JSON.parse(
                JSON.stringify(this.selectedData[i]).replace(
                  "imgUrl",
                  "carouselImgOne"
                )
              );
            }
          }
        });
      },
      close() {
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.go(-1);
        // this.$router.push({
        //   path: "/activity/info",
        //   query: {
        //     t: Date.now(),
        //   },
        // });
      },
      //确定选择商品
      multipleSelection(data) {
        this.selectedData = [];
        this.open = false;
        this.$nextTick(() => {
          this.selectedData = data;
        });
      },
      toCloseBox() {
        this.open = false;
      },
      /**
       * 商品选择页面，数据回显选中
       */
      selectProduct() {
        //获取除当前活动外，所有已上架的商品ID，排除处理
        let activityUid = this.form.activityUid;
        getInfoProUid(activityUid).then((response) => {
          this.proUids = response.data;
          console.log(this.proUids)
          this.$forceUpdate();
          this.open = true;

          this.$nextTick(() => {
            this.$refs["selTable"].greet(this.selectedData);
          });
        });
      },
      p(s) {
        return s < 10 ? "0" + s : s;
      },
      getSTime(val) {
        const d = new Date(val[0]);
        const resDate =
          d.getFullYear() +
          "-" +
          this.p(d.getMonth() + 1) +
          "-" +
          this.p(d.getDate());
        const resTime =
          this.p(d.getHours()) +
          ":" +
          this.p(d.getMinutes()) +
          ":" +
          this.p(d.getSeconds());
        this.form.beginTime = resDate + " " + resTime;
        const c = new Date(val[1]);
        const resDatec =
          c.getFullYear() +
          "-" +
          this.p(c.getMonth() + 1) +
          "-" +
          this.p(c.getDate());
        const resTimec =
          this.p(c.getHours()) +
          ":" +
          this.p(c.getMinutes()) +
          ":" +
          this.p(c.getSeconds());
        this.form.endTime = resDatec + " " + resTimec;
      },
    },
  };
</script>

<style scoped>
  .form-inline {
    width: 1200px;
    min-height: 100%;
    margin: 30px auto 0;
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;
    border: 1px solid #eee;
  }

  .el-radio.is-bordered {
    width: 185px;
    height: 70px;
    border: 1px dashed #ccc;
    margin-top: 13px;
  }

  .selectProduct {
     width: 90px;
    height: 30px;
    border: 1px dashed #ccc;
    text-align: center;
    line-height: 30px;
    color: #333;
  }

  .yhqBottom {
    position: fixed;
    bottom: 0;
    z-index: 10;
    left: 0;
    width: 100%;
    height: 68px;
    padding-left: 120px;
    box-shadow: 0 -2px 8px rgb(200 201 204 / 20%);
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
  }
</style>
